//
//  DFOAuthViewController.swift
//  新浪微博
//
//  Created by dafei on 16/5/22.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

//设置偏好设置保存 key
private let userInfoKey = "com.baidu.userInfoKey"


class DFOAuthViewController: UIViewController {
    
    //声明webview属性
    let webView = UIWebView()
    
    override func loadView() {
        //在loadview阶段 将跟视图替换为webview
        view = webView
        webView.opaque = false
        webView.backgroundColor = UIColor.whiteColor()
        
        
        //设置代理
        webView.delegate = self
        
    }
    
   override func viewDidLoad() {
        super.viewDidLoad()
        setNacBar()
        loadOauthPage()
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }

    //打开授权页面
    private func loadOauthPage() {
        //获取req对象      https://api.weibo.com/oauth2/authorize
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string:urlString)!
        let req = NSURLRequest(URL: url)
        webView.loadRequest(req)

    }
   
}


//设置导航条 监听按钮点击事件
extension DFOAuthViewController {


    private func setNacBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "返回", target: self, action: #selector(DFOAuthViewController.close))
    
    }

    @objc private func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    
    }


}


extension DFOAuthViewController: UIWebViewDelegate {

    //使用进度条加载进度
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    //授权成功之后 就会回调新页面 在回调的页面地址中会包含code (授权码)
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //打印url
        let urlString = request.URL?.absoluteString ?? ""
        //截取收取成功的字符串中的code
        //定义标记
        let successFlag = "code="
        if urlString.containsString(successFlag) {
        //授权成功
            // '!' 表示程序员 确保一定能够找到对应字符串所在位置
            let range = urlString.rangeOfString(successFlag)!
            let code = urlString.substringFromIndex(range.endIndex)
            print(code)
            //获取code 之后  请求token
//            loadAccessToken(code)
            DFUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) in
                
                if !isSuccess {
                
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                //请求成功
                //如果不dismiss 会在内存中一直存在
                self.dismissViewControllerAnimated(true, completion: {
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
                })
                
                
            })
            //不加载网页
          return false
        
        }
        return true
    }
    


}








